package com.lyx.crm.aspect;


import com.lyx.crm.annotation.RequiredPermission;
import com.lyx.crm.exceptions.AuthException;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpSession;
import java.util.List;

/**
 * @Package: com.lyx.crm.aspect
 * @ClassName: PermissionProxy
 * @Author: lyx
 * @CreateTime: 2021/9/8 21:27
 * @Description:
 */
@Component
@Aspect
public class PermissionProxy {

    @Autowired
    private HttpSession session;

    /**
     * 切面会拦截指定包下面的指定注解
     * com.lyx.crm.annotation.RequiredPermission
     *
     * @param pjp
     * @return
     */
    @Around(value = "@annotation(com.lyx.crm.annotation.RequiredPermission)")
    public Object around(ProceedingJoinPoint pjp) throws Throwable {
        Object result = null;

        List<String> permission = (List<String>) session.getAttribute("permission");
        if (null == permission || permission.size() < 1) {
            //抛出认证异常
            throw new AuthException();
        }

        //得到对应的目标方法
        MethodSignature methodSignature = (MethodSignature) pjp.getSignature();

        //得到方法上的注解
        RequiredPermission requiredPermission = methodSignature.getMethod().getDeclaredAnnotation(RequiredPermission.class);
        //判断注解上对应的状态码
        if(!permission.contains(requiredPermission.code())){
            //如果权限中不包含当前方法上注解指定的权限码，则抛出异常
            throw new AuthException();
        }

        result = pjp.proceed();
        return result;
    }
}
